<?php

require_once SHMS_CORE_PATH."/shms_core_form.inc";
require_once SHMS_CORE_PATH."/shms_core_common.inc";

function shms_cca_form_verify_user_access(&$form_state,$gyid){
  if(!isset($form_state['verification_done'])){
    $gq = db_select(SHMS_GROUP_BY_YEAR_TABLE,'gy'); $gq->condition("gy.id",$gyid);
    $gq->addField('gy', 'chair_pid');
    //$gq->innerJoin(SHMS_GROUP_TABLE,'g','gy.gid = g.id'); $gq->addField('g', 'chair_pid');
    $group = $gq->execute()->fetchAssoc();
    if(empty($group) || !shms_validate_group_access(NULL,$group['chair_pid'])){
      return FALSE;
    }
    $form_state['verification_done'] = TRUE;
  }
  return TRUE;
}

function shms_cca_form_get_basic_structure(){
  return array(
    'name' => array(
      '#type' => 'textfield',
      '#title'=> t("Name"),
      '#required' => TRUE,
    ),
    'description' => array(
      '#type' => 'textarea',
      '#title'=> t("Description"),
    ),
  );
}

function shms_cca_form_get_additional_structure(){
  $cca_type_list = shms_core_db_load_assoc_all_match(SHMS_GROUP_TABLE,'parent_gid','0','id');
  $option_arr = array();
  foreach($cca_type_list as $id => $info){
    $option_arr[$id] = $info['name'];
  }
  
  return array(
    'type' => array(
      '#type' => 'radios',
      "#required" => TRUE,
      '#title'=> t("Comm Classification"),
      '#options'=> array(
        'minor' => "Minor", 
        'intermediate' => 'intermediate',
        'super_inter' => "Super Intermediate",
        "major" => "Major", 
        "super_major" => "Super Major"
      ),
    ),
    'parent_gid' => array(
      '#type' => 'select',
      '#title'=> t("Type"),
      '#required' => TRUE,
      '#options'  => $option_arr,
    ),
    'cca_assignable' => array(
      '#type' => 'checkbox',
      '#title'=> t("CCA Points Assignable"),
      "#description"  => "If CCA Points not assignable, the group members would not be getting CCA points in this group",
      '#default_value'  => TRUE,
    ),
    'chair_pid' => array(
      '#type' => "textfield",
      '#title'=> t("Chair Person"),
      '#required' => TRUE,
      '#autocomplete_path'  => SHMS_PERSON_PATH."/name_auto_complete_matrix_keyed",
    ),
    'quota' => array(
      '#type' => "textfield",
      '#required' => TRUE,
      '#title'=> t("Quota for this CCA"),
    ),
  );
}

function  shms_core_cca_validate_chair_matric_and_change_it_to_person_id(&$form_state){
  $info_arr = explode(" - ", $form_state['values']['chair_pid']);
  $matric_no = array_pop($info_arr);
  if(!shms_core_person_matric_number_is_correct_format($matric_no)){
    form_set_error("chair_pid","Please Follow the Matric Number Format, or use the auto complete to complete");
    return;
  }
  
  // load person first
  $person_data = shms_core_db_load_from_table(SHMS_PERSON_TABLE,'matric_no', $matric_no);
  if(empty($person_data)){
    form_set_error("chair_pid","Sorry Person with matric number: ".$matric_no." doesn't exist.");
    return;
  }
  $form_state['values']['chair_pid'] = $person_data['id'];
}

function shms_core_cca_validate_name_exist(&$form_state){
  $qres = shms_core_db_load_from_table(SHMS_GROUP_TABLE,'name',$form_state['values']['name']);
  if(!empty($qres)){
    form_set_error('name',"CCA with the same name exists");
  }
}

function shms_core_cca_validate_quota_field($form_state){
  if(!preg_match("/^[0-9]+$/", $form_state['values']['quota'])){
    form_set_error("quota","Please Enter an Integer");
  }
}

function shms_cca_form_person_in_group_table($gyid,$mode = "view"){
  $add_subcom_str = l("Add Main Comm",SHMS_CCA_PATH."/".$gyid."/add_member/subcom");
  $add_member_str = l("Add Sub Comm",SHMS_CCA_PATH."/".$gyid."/add_member/member");
  
  // define the person list of the group
  $person_list = shms_core_db_get_person_info_list_from_gyid($gyid);
  
  $res_arr['member_list'] = array(
    '#type'  => "fieldset",
    "#title"=> t("Group Members"),
    "#theme" => "shms_cca_form_person_in_group_table",
    "#weight"=> 10,
    '#tree'  => TRUE,
  );
  $res_arr['member_list']['add_member'] = array("#markup" => 
    $add_subcom_str." | ".$add_member_str);
    
  $res_arr['member_list']['subcom']  = array();
  $res_arr['member_list']['member']  = array();
  
  foreach($person_list as $pyid => $record){
    $key = $record['pgyid'];
    
    $type = $record['is_com']?"subcom":"member";
    $res_arr['member_list'][$type][$key] = array(
      'name'  => array("#markup" => $record['full_name']),
      'matric_no' => array("#markup" => $record['matric_no']),
      'room_number' => array('#markup'  => $record['room_number']),
    );
    
    if($mode == "view"){
      $res_arr['member_list'][$type][$key]['position_name']  = 
        array('#markup'=>$record['position_name']);
      $res_arr['member_list'][$type][$key]['cca_points']  = 
        array('#markup'=>is_numeric($record['cca_points'])?$record['cca_points']:"Not Assigned Yet");
      $res_arr['member_list'][$type][$key]['comments']  = array('#markup'=>$record['comments']);
      $res_arr['member_list'][$type][$key]['option']  = 
        array('#markup' => l("remove",SHMS_CCA_PATH."/$gyid/remove_member/$key",array('query'=>array("destination"=>current_path()))));
    } else if($mode == "update_cca"){
      $res_arr['member_list'][$type][$key]['position_name'] = array(
        '#type' => "textfield",
        '#default_value'=> $record['position_name'],
        "#size" => 10,
      );
      $res_arr['member_list'][$type][$key]['cca_points'] = array(
        '#type' => "textfield",
        '#default_value'=> $record['cca_points'],
        "#size" => 5,
        '#element_validate' => array("shms_core_form_validate_number_field"),
      );
      $res_arr['member_list'][$type][$key]['comments']  = array(
        '#type' => "textarea",
        '#default_value'=> $record['comments'],
      );
      $res_arr['member_list'][$type][$key]['option'] = array('#markup' => "NONE");
    }
  };
  
  return $res_arr;
}

function theme_shms_cca_form_person_in_group_table($variables){
  $form = $variables['form']; 
  $header = array("Name","Matric No.","Room Number","Position","CCA Points","Comments","Option");
  $rows = array('subcom'=>array(),'member'=>array());
  foreach($form as $type=>$arr){
    if($type{0} == "#") continue;
    foreach($arr as $pyid => $record){
      if(!is_numeric($pyid))  continue;
      $rows[$type][] = array(
        drupal_render($record['name']),
        drupal_render($record['matric_no']),
        drupal_render($record['room_number']),
        drupal_render($record['position_name']),
        drupal_render($record['cca_points']),
        drupal_render($record['comments']),
        drupal_render($record['option']),
      );
    }
  }
  $trailing_ele = drupal_render($form['add_member']);
  $res = "";
  if(!empty($rows['subcom'])){
    $res .= "Subcom:".theme("table",array('header'=>$header,"rows"=>$rows['subcom']));
  }
  if(!empty($rows['member'])){
    $res .= "Member:".theme("table",array('header'=>$header,"rows"=>$rows['member']));
  }
  return $res.$trailing_ele;
}

function shms_cca_form_remove_person_from_group($form,&$form_state){
  $triggering_ele_info = $form_state['triggering_element']['#attributes'];
  drupal_set_message("<pre>".print_r($triggering_ele_info ,TRUE)."</pre>","error");
  if($triggering_ele_info['action'] != "remove"){
    drupal_set_message("Wrong button clicked. No effect.","error");
    return;
  }
  if(shms_db_cca_remove_person_from_group($triggering_ele_info['pyid'],$triggering_ele_info['gyid'])){
    drupal_set_message("Remove Person succeeded.");
  } else{
    drupal_set_message("Remove Person failed.","error");
  }
}

